<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="SQLite,">










<meta name="description" content="这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来">
<meta name="keywords" content="SQLite">
<meta property="og:type" content="article">
<meta property="og:title" content="android课程学习之写个操作数据库的小框架">
<meta property="og:url" content="http://Anzusen.com/2020/04/06/android课程学习之写个操作数据库的小框架/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/sqliteframe_view.png">
<meta property="og:updated_time" content="2020-04-09T04:02:03.167Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="android课程学习之写个操作数据库的小框架">
<meta name="twitter:description" content="这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来">
<meta name="twitter:image" content="http://anzusen.com/image/sqliteframe_view.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2020/04/06/android课程学习之写个操作数据库的小框架/">





  <title>android课程学习之写个操作数据库的小框架 | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2020/04/06/android课程学习之写个操作数据库的小框架/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">android课程学习之写个操作数据库的小框架</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-06T12:35:59+08:00">
                2020-04-06
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/android/" itemprop="url" rel="index">
                    <span itemprop="name">android</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/android/数据库/" itemprop="url" rel="index">
                    <span itemprop="name">数据库</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/04/06/android课程学习之写个操作数据库的小框架/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/04/06/android课程学习之写个操作数据库的小框架/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来"><a href="#这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来" class="headerlink" title="这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来"></a>这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来</h1><a id="more"></a>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><blockquote>
<p>Android中，操作数据库有很多模板代码，请将之整合为一个小框架，让使用者能轻松去使用数据库提供的相关功能。</p>
</blockquote>
<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><ol>
<li>考虑到使用者创建数据库的多样性，我们肯定无法猜测到使用者创建的数据库表格的每一个列名（非关系型数据库叫 字段），或者说去统计一下大部分创建数据库用到哪些列名，更不可能写一个固定列名的数据库供使用者使用，这样就失去框架的意义了，但是，我们可以通过类来实现，也就是用框架诱导使用者自定义一个类，向框架的成员函数传入这个类或者类声明的对象，实现数据库的增删改查操作。</li>
<li>用户自定义类的成员变量类型 如何转换为对应的SQLite数据库数据类型。SQLite保存数据时，支持NULL（零）、INTEGER（整数）、 REAL（浮点数字）、TEXT（字符串文本）和BLOB（二进制对 象）五种数据类型。实际上SQLlite也接受varchar(n)、char(n)等数据类型，只不过会转化为5种数据类型。     </li>
</ol>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><p> 如图所示，我的想法就是通过简单的5个按钮点击事件中调用我写的框架函数实现数据库的创建、插入、查询、更新和删除操作<br> <img src="/image/sqliteframe_view.png" alt></p>
<h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><h4 id="自定义sqlite类"><a href="#自定义sqlite类" class="headerlink" title="自定义sqlite类"></a>自定义sqlite类</h4><p> 安卓中的SQLite数据库的创建是通过创建SQLiteOpenHelper类的子类，并且重写onCreate()和onUpgarde()方法，当这个子类实现的时候就会自动回调onCreate方法执行sql语句实现创建数据库。</p>
<p> 所以首先写了一个单独的mysqlite类继承自SQLiteOpenHelper类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">package</span> com.example.sqliteframe;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> android.content.Context;</span><br><span class="line"><span class="keyword">import</span> android.database.sqlite.SQLiteDatabase;</span><br><span class="line"><span class="keyword">import</span> android.database.sqlite.SQLiteOpenHelper;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySqlite</span> <span class="keyword">extends</span> <span class="title">SQLiteOpenHelper</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String dbName = <span class="string">"test_sql"</span>; <span class="comment">//数据库名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String sql; <span class="comment">//创建表单的sql语句</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MySqlite</span><span class="params">(Context context ,String _sql)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(context, dbName, <span class="keyword">null</span>, <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">this</span>.sql=_sql;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MySqlite</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(context, dbName, <span class="keyword">null</span>, <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(SQLiteDatabase db)</span> </span>&#123;</span><br><span class="line">       db.execSQL(sql);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onUpgrade</span><span class="params">(SQLiteDatabase db, <span class="keyword">int</span> oldVersion, <span class="keyword">int</span> newVersion)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>数据库的名字 我就直接声明为静态常量了，我希望使用我这个框架的数据库就为这个名字。避免需要传入数据库名字这个参数导致参数过多。</li>
<li>因为数据库表格的创建需要列名及其数据类型，需要传入sql这个参数，于是我重写了构造函数，除了执必要的的操作外，还需要将传入的sql参数赋值给MySqlite类的成员变量sql。然后在onCreate()回调函数中使用并执行该sql语句。该类的所有操作结束。</li>
</ol>
<h4 id="静态的创建数据库方法"><a href="#静态的创建数据库方法" class="headerlink" title="静态的创建数据库方法"></a>静态的创建数据库方法</h4><ol>
<li>创建自定义的框架类 AnanFrame.java</li>
<li><p>该类的第一个静态成员函数 ：CreateDB()  创建数据库 。创建数据库的sql语句需要表名和各个列名，所以需要传入 tableName 和 使用者自定义类的类类型 clazz ,context这个参数是上下文，这是andriod一般都需要的参数（创建自定义的Mysqlite类对象时需要该参数）。如果你对java中的Class这个类不是很懂得话可以先看看下面的链接：<br><a href="https://blog.csdn.net/dufufd/article/details/80537638" target="_blank" rel="noopener">Java中Class对象详解</a></p>
</li>
<li><p>首先我们需要解析一下传入的class类，为了解析类需要使用到java 反射当中 Field这个类，简单介绍一下这个类：<br>Field是一个可以获取当前类或者类对象的成员变量的类型的一个类。<br>我们要用到的方法：</p>
</li>
</ol>
<ul>
<li>Class.getFields(): 获取类中public访问权限的属性，返回一个包含某些 Field 对象的数组。</li>
<li>Class.getDeclaredFields(): 获取类中所有的属性(public、protected、default、private)，但不包括继承的属性，返回 Field 对象的一个数组。（因为无法预测用户定义的成员访问权限，故采用该方法）</li>
<li>Field.getType()：返回这个变量的类型</li>
<li>getName() ： 获取属性的名字</li>
<li>get(Object obj) 返回指定对象obj上此 Field 表示的字段的值</li>
</ul>
<ol start="4">
<li>因为java中的数据类型和sqlite数据库的数据类型不同，所以需要转换一下，我写成了一个叫translateType的函数，也就是将java数据类型转化为字符串然后返回对应的sqlite数据类型字符串。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取类的数据类型并返回其对应的数据库数据类型  这里只是写了一些常用的类型 实际需要写完整一些更好</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">translateType</span><span class="params">(String string)</span></span>&#123;</span><br><span class="line">     <span class="keyword">if</span> (string.equals(<span class="string">"class java.lang.Integer"</span>)||string.equals(<span class="string">"int"</span>) )</span><br><span class="line">         <span class="keyword">return</span>  <span class="string">"integer"</span>;</span><br><span class="line">     <span class="keyword">else</span> <span class="keyword">if</span>(string.equals(<span class="string">"class java.lang.String"</span>))</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"varchar(100)"</span>;</span><br><span class="line">     <span class="keyword">else</span> <span class="keyword">if</span> (string.equals(<span class="string">"class java.lang.Float"</span>))</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"float"</span>;</span><br><span class="line">     <span class="keyword">else</span> <span class="keyword">if</span> (string.equals(<span class="string">"class java.lang.Double"</span>))</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"double"</span>;</span><br><span class="line">     <span class="keyword">else</span></span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li><p>准备工作做好以后，我们来看这个函数的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建数据库 参数分别是：上下文 表名 类名</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span>  <span class="keyword">void</span> <span class="title">CreateDB</span><span class="params">(Context context,String tableName ,Class clazz)</span></span>&#123;</span><br><span class="line">      Field[] fields = clazz.getDeclaredFields();</span><br><span class="line">      String sql=<span class="string">"create table "</span>+tableName+<span class="string">" (id integer primary key autoincrement,"</span>;</span><br><span class="line">      <span class="keyword">for</span> (Field field : fields)</span><br><span class="line">      &#123;</span><br><span class="line">          <span class="comment">// 对于每个属性，获取成员名</span></span><br><span class="line">          String varName = field.getName();</span><br><span class="line">          Type type= field.getType();</span><br><span class="line">          sql = sql.concat(varName+<span class="string">' '</span>+translateType(type.toString())+<span class="string">","</span>);</span><br><span class="line">          System.out.println(<span class="string">"变量 "</span> + varName + <span class="string">" 的类型为："</span> + translateType(type.toString()));</span><br><span class="line">      &#125;</span><br><span class="line">      sql=sql.substring(<span class="number">0</span>,sql.length()-<span class="number">1</span>).concat(<span class="string">")"</span>);</span><br><span class="line">      System.out.println(sql);</span><br><span class="line">      MySqlite mySqlite = <span class="keyword">new</span> MySqlite(context,sql);</span><br><span class="line">      System.out.println(<span class="string">"\n***********创建数据成功*******************************\n"</span>);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>我们获取类的所有成员属性并且存入Field[]数组，然后for循环解析这个数组，在for循环中，通过 field.getName()获取属性的名字，通过field.getType()获取属性的类型。然后根据sql语句创建的格式不断增加列名和列类型（类型需要转化）。解析完所有成员以后，规范一下sql语句格式，然后作为参数传入自定义的创建sqlite数据库类的构造方法，即可回调onCreate()方法完成数据库的创建。</p>
</li>
</ol>
<h3 id="增"><a href="#增" class="headerlink" title="增"></a>增</h3><ol>
<li>插入一条数据，通过传入使用者自定义的类声明的对象完成插入一条数据。为了获取对象的成员变量的值，跟上面解析类一样，我们需要解析传入的类对象，为了提高代码的复用性，我将他写成了一个解析对象函数parseObject()，返回类型为ContentValues这个存储数据类型（ContentValues类类似于Map类，通过键值对的形式存入数据，这里的key表示插入数据的列名，value 表示要插入的数据。），因为安卓中提供了一个 sqLiteDatabase.insert()方法插入一行数据，该函数的第三个参数就是ContentValues类型的，如下：</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//解析一个对象 并返回ContentValues类型</span></span><br><span class="line"><span class="function"><span class="keyword">public</span>  <span class="keyword">static</span> ContentValues <span class="title">parseObject</span><span class="params">(Object object)</span></span>&#123;</span><br><span class="line">    Field[] fields = object.getClass().getDeclaredFields();</span><br><span class="line">    ContentValues values = <span class="keyword">new</span> ContentValues();</span><br><span class="line">    System.out.println(<span class="string">"\n 类对象的成员变量对应的值如下\n"</span>);</span><br><span class="line">    <span class="keyword">for</span> (Field field : fields)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// 对于每个属性，获取成员名</span></span><br><span class="line">        String varName = field.getName();</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">boolean</span> access = field.isAccessible();</span><br><span class="line">            <span class="keyword">if</span>(!access) field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">            <span class="comment">//从obj中获取field变量</span></span><br><span class="line">            Object o = field.get(object);</span><br><span class="line">            System.out.println(<span class="string">"变量: "</span> + varName + <span class="string">" = "</span> + o.toString());</span><br><span class="line">            values.put(varName,o.toString());</span><br><span class="line">            <span class="keyword">if</span>(!access) field.setAccessible(<span class="keyword">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Exception ex)</span><br><span class="line">        &#123;</span><br><span class="line">            ex.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> values;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>在插入函数中，通过getWritableDatabase()方法得到可写入的SQLiteDatabase 对象，然后将获得的ContentValues对象传入insert()方法中。<br>insert()方法接收3个参数，第一个参数是数据表的名称，第二个参数表示如果发现将要插入的行为空行时，会将这个列名的值设为null, 第三个参数为ContentValues对象。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//数据库插入一条数据  类创建的对象</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">InsertDB</span><span class="params">(Context context,String tableName ,Object object)</span></span>&#123;</span><br><span class="line">    ContentValues contentValues = parseObject(object);</span><br><span class="line"></span><br><span class="line">    MySqlite mySqlite = <span class="keyword">new</span> MySqlite(context);</span><br><span class="line">    SQLiteDatabase sqLiteDatabase = mySqlite.getWritableDatabase();</span><br><span class="line">    sqLiteDatabase.insert(tableName ,<span class="keyword">null</span>,contentValues);</span><br><span class="line">    System.out.println(<span class="string">"\n***********插入数据成功*******************************\n"</span>);</span><br><span class="line">    sqLiteDatabase.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>需要注意的是，使用完SQLiteDatabase对象后一定要调用close()方法关闭，否则数据库连接会一直存在，不断消耗内存，当系统内存不足时将获取不到SQLiteDatabase对象，并且会报出数据库未关闭异常。</li>
</ol>
<h3 id="查"><a href="#查" class="headerlink" title="查"></a>查</h3><ol>
<li><p>为了能够马上检查到插入的数据是否成功，所以首先讲一下查询操作。当然你也可以通过可视化的软件（navicat或者SQLite Expert Personal）查看，如果你在使用可视化软件当中遇到两个软件操作同一数据库不能同步更新的问题，欢迎查看我之前制作的视频来解决：<br><a href="https://b23.tv/BV1r741117hA" target="_blank" rel="noopener">android studio 和navicat 操作同一数据库同步更新的问题</a></p>
</li>
<li><p>查询操作，通过游标一行一行的获取数据，并且获得每一列的列名及其值，然后打印出来。为了通过列名获取索引列号，然后通过索引号得到对应的值，我们任然需要解析传入的类。</p>
</li>
<li>通过getReadableDatabase()方法得到可读取的SQLiteDatabase 对象，用query()方 法查询表中的数据，query()方法接收7个参数，第一个参数表示表名称，第二个参数表示查询的列名，第三个参数接收查询条件子句，第四个参数接收查询子句对应的条件值，第五个参数表示分组方式，第六个参数接收having条件，即定义组的过滤器，第七个参数表示排序方式。<br>查询数据库代码如下：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//查询所有数据  参数分别是 内容 表格名 类名</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">QuaryDB</span><span class="params">(Context context,String tableName ,Class clazz)</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">"\n***********查询结果如下*******************************\n"</span>);</span><br><span class="line">      MySqlite mySqlite = <span class="keyword">new</span> MySqlite(context);</span><br><span class="line">      SQLiteDatabase sqLiteDatabase = mySqlite.getReadableDatabase();</span><br><span class="line">      Field[] fields = clazz.getDeclaredFields();</span><br><span class="line">      Cursor cursor = sqLiteDatabase.query(tableName,</span><br><span class="line">              <span class="keyword">null</span>,<span class="keyword">null</span>,<span class="keyword">null</span>,</span><br><span class="line">              <span class="keyword">null</span>,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">while</span> (cursor.moveToNext())&#123;</span><br><span class="line">          String string = <span class="keyword">new</span> String();</span><br><span class="line">          <span class="keyword">for</span> (Field field : fields)</span><br><span class="line">          &#123;</span><br><span class="line">              <span class="comment">// 对于每个属性，获取成员名</span></span><br><span class="line">              String varName = field.getName();</span><br><span class="line">              string = string.concat(varName+<span class="string">":"</span>+cursor.getString(cursor.getColumnIndex(varName))+<span class="string">"  "</span>);</span><br><span class="line">          &#125;</span><br><span class="line">          System.out.println(<span class="string">"\n"</span>+string+<span class="string">"\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">      System.out.println(<span class="string">"\n***********查询成功*******************************\n"</span>);</span><br><span class="line">      sqLiteDatabase.close();</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="改"><a href="#改" class="headerlink" title="改"></a>改</h3><ol>
<li>通过getWritableDatabase()方法得到可写入的SQLiteDatabase 对象，然后调用updata()函数，update()方法接收4个参数，第一个参数表示表名，第二个参数接收一个ContentValues对象，第三个参数为可选的where语句，第四个参数表示whereClause语句中表达式的占位参数列表,这些字符串会替换掉where条件中的“?”。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据条件更新数据   传入参数分别是 上下文  表名 类对象 对象的一个属性及其值作为更新条件</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">UpdateDB</span><span class="params">(Context context,String tableName ,Object object,String key,String value)</span></span>&#123;</span><br><span class="line">       ContentValues contentValues = parseObject(object);</span><br><span class="line">       contentValues.remove(key);  <span class="comment">//剔除条件</span></span><br><span class="line">       MySqlite mySqlite = <span class="keyword">new</span> MySqlite(context);</span><br><span class="line">       SQLiteDatabase sqLiteDatabase = mySqlite.getWritableDatabase();</span><br><span class="line">       <span class="keyword">int</span> a=sqLiteDatabase.update(tableName,contentValues,key+<span class="string">"=?"</span>,<span class="keyword">new</span> String[]&#123;value&#125;);</span><br><span class="line">       System.out.println(<span class="string">"\n***********更新数据成功******************************\n"</span>);</span><br><span class="line">       sqLiteDatabase.close();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h3 id="删"><a href="#删" class="headerlink" title="删"></a>删</h3><ol>
<li>删除操作是通过sql语句实现的，需要注意删除条件的值需要用<strong>单引号</strong>括起来。如果用户传入的键值为空就删除整个数据库的数据，不为空删除一条数据。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据 键值对 条件删除数据  如果 key或者value中有一个为null，就删除所有数据</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">DeleteDB</span><span class="params">(Context context,String tableName ,String key,String value)</span></span>&#123;</span><br><span class="line">        MySqlite mySqlite = <span class="keyword">new</span> MySqlite(context);</span><br><span class="line">        SQLiteDatabase sqLiteDatabase = mySqlite.getWritableDatabase();</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">null</span>==key || <span class="keyword">null</span> == value) &#123;</span><br><span class="line">            sqLiteDatabase.delete(tableName, <span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">            System.out.println(<span class="string">"\n***********所有数据删除成功******************************\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span>&#123;</span><br><span class="line">            sqLiteDatabase.execSQL(<span class="string">"delete from "</span>+tableName+<span class="string">" where "</span>+key+<span class="string">"= '"</span>+value+<span class="string">"'"</span>);</span><br><span class="line">            System.out.println(<span class="string">"\n***********一条数据删除成功******************************\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        sqLiteDatabase.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="使用自定义框架"><a href="#使用自定义框架" class="headerlink" title="使用自定义框架"></a>使用自定义框架</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.example.sqliteframe;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> androidx.appcompat.app.AppCompatActivity;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> android.os.Bundle;</span><br><span class="line"><span class="keyword">import</span> android.view.View;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">AppCompatActivity</span> </span>&#123;</span><br><span class="line">    String tableName=<span class="string">"sql"</span>;</span><br><span class="line">    <span class="comment">//使用者自定义类数组</span></span><br><span class="line">    Mytest []mytest=&#123;<span class="keyword">new</span> Mytest(<span class="string">"anan"</span>,<span class="number">18</span>,<span class="string">"15707254047"</span>),</span><br><span class="line">                     <span class="keyword">new</span> Mytest(<span class="string">"bnbn"</span>,<span class="number">20</span>,<span class="string">"15703044048"</span>),</span><br><span class="line">                     <span class="keyword">new</span> Mytest(<span class="string">"cncn"</span>,<span class="number">19</span>,<span class="string">"15707252037"</span>)&#125;;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//点击创建数据库按钮</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clickCreateDB</span><span class="params">(View view)</span></span>&#123;</span><br><span class="line">    	<span class="comment">//通过对象获取类名</span></span><br><span class="line">        AnanFrame.CreateDB(MainActivity.<span class="keyword">this</span>,tableName,mytest[<span class="number">0</span>].getClass());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//点击插入数据库按钮</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clickInsertDB</span><span class="params">(View view)</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">3</span>;i++) &#123;</span><br><span class="line">            AnanFrame.InsertDB(MainActivity.<span class="keyword">this</span>, tableName, mytest[i]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clickQueryDB</span><span class="params">(View view)</span></span>&#123;</span><br><span class="line">        AnanFrame.QuaryDB(MainActivity.<span class="keyword">this</span>,tableName,mytest[<span class="number">0</span>].getClass());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clickDeleteDB</span><span class="params">(View view)</span></span>&#123;</span><br><span class="line">        <span class="comment">//删除一条</span></span><br><span class="line">        AnanFrame.DeleteDB( MainActivity.<span class="keyword">this</span>,tableName,<span class="string">"name"</span>,mytest[<span class="number">1</span>].name);</span><br><span class="line">        <span class="comment">//删除所有</span></span><br><span class="line"><span class="comment">//        AnanFrame.DeleteDB( MainActivity.this,tableName,null,null);</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clickUpdateDB</span><span class="params">(View view)</span></span>&#123;</span><br><span class="line">        Mytest mytest4=<span class="keyword">new</span> Mytest(<span class="string">"cncn"</span>,<span class="number">21</span>,<span class="string">"157003044047"</span>);</span><br><span class="line">        AnanFrame.UpdateDB(MainActivity.<span class="keyword">this</span>,tableName,mytest4,<span class="string">"name"</span>,<span class="string">"cncn"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用者自定义类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mytest</span> </span>&#123;</span><br><span class="line">    String name;</span><br><span class="line">    <span class="keyword">int</span> age;</span><br><span class="line">    String phone;</span><br><span class="line">    Mytest(String _name,<span class="keyword">int</span> _age,String _phone)&#123;</span><br><span class="line">        <span class="keyword">this</span>.name=_name;</span><br><span class="line">        <span class="keyword">this</span>.age=_age;</span><br><span class="line">        <span class="keyword">this</span>.phone=_phone;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后项目的代码我已经上传到仓库了，地址如下：<br> <a href="https://gitee.com/anzhusen/androidLearning/tree/master/sqliteFrame" target="_blank" rel="noopener">sqliteFrame项目地址</a></p>
<h2 id="小欢喜"><a href="#小欢喜" class="headerlink" title="小欢喜"></a>小欢喜</h2><p>因为github是国外的，有时候访问博客一直访问不到，于是找了篇迁移博客的教程，决定把博客地址从github迁移到gitee上，操作成功了！访问速度不知快了多少（笑哭），下面是教程地址，感谢这个博主：</p>
<p><a href="https://blog.csdn.net/qq_42994651/article/details/104318497?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5&amp;utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5" target="_blank" rel="noopener">hexo博客从github迁移到gitee</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SQLite/" rel="tag"># SQLite</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/02/22/android课程学习之回忆java事件处理/" rel="next" title="事件处理">
                <i class="fa fa-chevron-left"></i> 事件处理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/09/JavaWeb课程学习之include思想无处不在/" rel="prev" title="JavaWeb课程学习之include思想无处不在">
                JavaWeb课程学习之include思想无处不在 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来"><span class="nav-number">1.</span> <span class="nav-text">这是大三时期安卓课程布置的一次作业练习，在实现的过程中觉得蛮有趣的，于是通过这篇博客记录下来</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#题目"><span class="nav-number">1.1.</span> <span class="nav-text">题目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分析"><span class="nav-number">1.2.</span> <span class="nav-text">分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现"><span class="nav-number">1.3.</span> <span class="nav-text">实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建"><span class="nav-number">1.3.1.</span> <span class="nav-text">创建</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义sqlite类"><span class="nav-number">1.3.1.1.</span> <span class="nav-text">自定义sqlite类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#静态的创建数据库方法"><span class="nav-number">1.3.1.2.</span> <span class="nav-text">静态的创建数据库方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#增"><span class="nav-number">1.3.2.</span> <span class="nav-text">增</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查"><span class="nav-number">1.3.3.</span> <span class="nav-text">查</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#改"><span class="nav-number">1.3.4.</span> <span class="nav-text">改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删"><span class="nav-number">1.3.5.</span> <span class="nav-text">删</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用自定义框架"><span class="nav-number">1.3.6.</span> <span class="nav-text">使用自定义框架</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小欢喜"><span class="nav-number">1.4.</span> <span class="nav-text">小欢喜</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
